import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, logout as logoutApi, getUserInfo } from '@/api/auth'
import { useCartStore } from './cart'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const userInfo = ref(null)
  const role = ref('') // 'customer', 'employee', 'admin'

  // 计算属性：是否已登录
  const isLoggedIn = computed(() => !!token.value)
  
  // 计算属性：权限判断
  const isCustomer = computed(() => role.value === 'customer')
  const isEmployee = computed(() => role.value === 'employee')
  const isAdmin = computed(() => role.value === 'admin')

  // 从本地存储初始化
  const initFromStorage = () => {
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    const storedRole = localStorage.getItem('role')
    
    if (storedToken) {
      token.value = storedToken
      userInfo.value = storedUserInfo ? JSON.parse(storedUserInfo) : null
      role.value = storedRole || ''
    }
  }

  // 登录
  const login = async (credentials) => {
    try {
      const res = await loginApi(credentials)
      
      // 检查响应格式
      if (res.code === 200 && res.data) {
        token.value = res.data.token
        userInfo.value = res.data.userInfo
        role.value = res.data.role
        
        // 保存到本地存储
        localStorage.setItem('token', token.value)
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        localStorage.setItem('role', role.value)
        
        // 初始化购物车（顾客登录后）
        if (role.value === 'customer') {
          try {
            const cartStore = useCartStore()
            cartStore.init()
          } catch (error) {
            console.error('初始化购物车失败', error)
          }
        }
        
        return res
      } else {
        throw new Error(res.message || '登录失败')
      }
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('登出失败', error)
    } finally {
      token.value = ''
      userInfo.value = null
      role.value = ''
      
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('role')
      
      // 清空购物车
      try {
        const cartStore = useCartStore()
        cartStore.reset()
      } catch (error) {
        console.error('清空购物车失败', error)
      }
    }
  }

  // 更新用户信息
  const updateUserInfo = (info) => {
    userInfo.value = { ...userInfo.value, ...info }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  return {
    token,
    userInfo,
    role,
    isLoggedIn,
    isCustomer,
    isEmployee,
    isAdmin,
    initFromStorage,
    login,
    logout,
    updateUserInfo
  }
})











